<script setup>
import {ref, onMounted, onUnmounted} from "vue";
import router from "@/router/index.js";
import {
  addBrowseRecord,
  cancelCollectApp,
  collectApp,
  deleteApp,
  queryAppDetailById,
  updateAppAnalysisAuth
} from "@/api/app.js";
import {Message, Notification} from "@arco-design/web-vue";
import UserInfoComponent from "@/components/UserInfoComponent.vue";
import AppUserAnalysis from "@/components/AppUserAnalysis.vue";
import AppResultAnalysis from "@/components/AppResultAnalysis.vue";
import {queryAppResultAnalysis, queryAppUserAnswerAnalysis} from "@/api/analysis.js";
import ShareModal from "@/components/ShareModal.vue";

const appDetail = ref({
  // id
  id: '',
  // 应用名
  appName: '',
  // 应用描述
  appDesc: '',
  // 应用封面
  appIcon: '',
  // 应用类型（0-得分类，1-测评类）
  appType: null,
  // 评分策略（0-自定义，1-AI）
  scoringStrategy: null,
  // 审核状态：0-待审核, 1-通过, 2-拒绝
  reviewStatus: null,
  // 所属分类id
  categoryId: '',
  // 应用分类
  appCategory: '',
  // 创建用户 id
  userId: '',
  // 创建者昵称
  nickname: '',
  // 创建者头像
  avatar: '',
  // 创建时间
  createTime: null,
  // 是否为该应用创建者
  isCreateUser: false,
  // 分析权限
  analysisAuth: null,
  // 是否为收藏者
  collectFlag: false
})
const id = ref(0)
const analysisVariable = ref(false)

const getAppDetail = () => {
  // 获取路由中的id
  const params = router.currentRoute.value.params
  id.value = params.id
  queryAppDetailById(id.value)
    .then(res => {
      if (res.data.code === 1) {
        appDetail.value = res.data.data
        analysisVariable.value = appDetail.value.analysisAuth === 0 && appDetail.value.isCreateUser === false
        if (!analysisVariable.value) {
          // 查询应用分析
          getUserRankData()
          getResultPieData()
        }
      }
    })
    .catch(error => {
      console.log(error)
    })
}

const onClickStartAnswer = () => {
  if (appDetail.value.reviewStatus !== 1) {
    Message.warning('该应用未过审！')
    return
  }
  if (appDetail.value.scoringStrategy === 1) {
    Notification.warning({
      title: '提示',
      content: '该应用为AI评分策略，将会对tokens产生一定的消耗',
      closable: true,
      duration: 0
    })
  }
  router.push(`/answer/${id.value}`)
}


const deleteDialog = ref(false)
const onClickDelete = () => {
  deleteDialog.value = true
}

const handleDelete = () => {
  deleteApp(id.value)
    .then(res => {
      if (res.data.code === 1) {
        Message.success('删除成功！')
        deleteDialog.value = false
        router.push('/')
      } else {
        Message.error('删除失败！')
      }
    })
    .catch(error => {
      console.log(error)
    })
}

let browseTimeout = null; // 定义一个变量存储定时器

onMounted(() => {
  getAppDetail()
  // 滚动到页面顶部
  window.scrollTo({
    top: 0,
    behavior: 'instant'
  });

  // 设置一个 2 秒的定时器
  browseTimeout = setTimeout(() => {
    const params = router.currentRoute.value.params;
    const appId = params.id; // 获取当前应用的 ID
    addBrowseRecord(appId)
  }, 2000); // 延迟 2 秒
});

onUnmounted(() => {
  // 如果用户在 2 秒内离开页面，清除定时器
  if (browseTimeout) {
    clearTimeout(browseTimeout);
  }
});

const authLoading = ref(false)

const setAnalysisAuth = async (val) => {
  let status
  if (val) {
    status = 1
  } else {
    status = 0
  }
  try {
    authLoading.value = true
    const res = await updateAppAnalysisAuth(id.value, status)
    if (res.data.code === 1) {
      Message.success('设置成功')
    }
  } catch (error) {
    console.log(error)
  } finally {
    authLoading.value = false
  }
}

// 数据
const userRankData = ref([])

const resultPieData = ref([])

const getUserRankData = async () => {
  try {
    const res = await queryAppUserAnswerAnalysis(id.value)
    if (res.data.code === 1) {
      userRankData.value = res.data.data.analysisList
    } else {
      Message.error('获取数据失败')
    }
  } catch (error) {
    console.log(error)
  }
}

const getResultPieData = async () => {
  try {
    const res = await queryAppResultAnalysis(id.value)
    if (res.data.code === 1) {
      resultPieData.value = res.data.data.analysisList
    } else {
      Message.error('获取数据失败')
    }
  } catch (error) {
    console.log(error)
  }
}

const onClickCollectApp = async () => {
  if (appDetail.value.reviewStatus !== 1) {
    Message.warning('该应用未过审！')
    return
  }
  try {
    const res = await collectApp(id.value)
    if (res.data.code === 1) {
      Message.success('收藏成功')
      appDetail.value.collectFlag = true
    } else {
      Message.error('收藏失败')
    }
  } catch (error) {
    console.log(error)
  }
}

const onClickCancelCollectApp = async () => {
  if (appDetail.value.reviewStatus !== 1) {
    Message.warning('该应用未过审！')
    return
  }
  try {
    const res = await cancelCollectApp(id.value)
    if (res.data.code === 1) {
      Message.success('取消收藏成功')
      appDetail.value.collectFlag = false
    } else {
      Message.error('取消收藏失败')
    }
  } catch (error) {
    console.log(error)
  }
}

// 分享弹窗引用
const shareModalRef = ref();
// 分享链接
const shareLink = `${window.location.protocol}//${window.location.host}/#/app/${router.currentRoute.value.params.id}`;
// 分享
const doShare = () => {
  if (shareModalRef.value) {
    shareModalRef.value.openModal();
  }
};
</script>

<template>
  <div id="app-detail-page">
    <a-card class="card">
      <div class="app-container">
        <div class="app-icon mobile-only">
          <a-image v-if="appDetail.appIcon" :src="appDetail.appIcon" alt="应用图标" width="240"/>
          <a-image v-else
                   width="240" height="200"
                   src="some-error.png"
          />
        </div>
        <div class="app-info">
          <div class="app-name">{{ appDetail.appName }}</div>
          <div class="app-desc">{{ appDetail.appDesc }}</div>
          <div class="app-action">
            <a-tag v-if="appDetail.reviewStatus === 1" color="green">已过审</a-tag>
            <a-tag v-else color="orange">待审核</a-tag>
          </div>
          <div class="app-other">
            <p>应用类型:
              <a-tag v-if="appDetail.appType === 1" color="green">测评类</a-tag>
              <a-tag v-else-if="appDetail.appType === 0" color="red">得分类</a-tag>
            </p>
            <p>评分策略:
              <a-tag v-if="appDetail.scoringStrategy === 1" color="blue">AI</a-tag>
              <a-tag v-else-if="appDetail.scoringStrategy === 0" color="orange">自定义</a-tag>
            </p>
            <p>所属分类: {{ appDetail.appCategory }}</p>
            <p>创建时间: {{ appDetail.createTime }}</p>

          </div>
          <user-info-component :avatar="appDetail.avatar" :nickname="appDetail.nickname" :userId="appDetail.userId"/>
          <div class="btn">
            <a-button type="primary" @click="onClickStartAnswer">开始答题</a-button>
            <a-button v-if="!appDetail.collectFlag" status="warning" type="primary" @click="onClickCollectApp">
              收藏应用
            </a-button>
            <a-button v-if="appDetail.collectFlag" status="warning" type="outline" @click="onClickCancelCollectApp">
              取消收藏
            </a-button>
            <a-button @click="doShare">分享应用</a-button>
            <a-popconfirm
              content="如果更新题目，过审应用将会重新进入审核状态"
              @ok="router.push(`/question/${id}`)"
            >
              <a-badge text="AI" v-if="appDetail.isCreateUser">
                <a-button type='outline' v-if="appDetail.isCreateUser">设置题目
                </a-button>
              </a-badge>
            </a-popconfirm>
            <a-popconfirm
              content="如果更新评分，过审应用将会重新进入审核状态"
              @ok="router.push(`/score/${id}`)"
            >
              <a-badge text="AI" v-if="appDetail.isCreateUser">
                <a-button type='outline' v-if="appDetail.isCreateUser">设置评分
                </a-button>
              </a-badge>
            </a-popconfirm>
            <a-popconfirm
              content="如果更新应用，过审应用将会重新进入审核状态"
              @ok="router.push(`/edit/${id}`)"
            >
              <a-button type='outline' v-if="appDetail.isCreateUser">编辑应用
              </a-button>
            </a-popconfirm>
            <a-button type='outline' v-if="appDetail.isCreateUser" @click="router.push(`/answer/record/${id}`)">回答记录
            </a-button>
            <a-button type="primary" v-if="appDetail.isCreateUser" @click="onClickDelete" status="danger">删除应用
            </a-button>
            <a-button @click="router.push('/')">返回主页</a-button>
          </div>
        </div>
        <!-- 应用图标 -->
        <div class="app-icon desk">
          <a-image v-if="appDetail.appIcon" :src="appDetail.appIcon" alt="应用图标" width="240"/>
          <a-image v-else
                   width="240" height="200"
                   src="some-error.png"
          />
        </div>
      </div>
    </a-card>

    <a-card v-if="!analysisVariable" class="app-analyze-card">
      <div class="title">
        <div class="text">
          答题应用分析
        </div>
        <div v-if="appDetail.isCreateUser" class="btn">
          允许他人查看
          <a-switch
            :loading="authLoading"
            v-model="appDetail.analysisAuth"
            :checked-value="1"
            :unchecked-value="0"
            @change="setAnalysisAuth"
          >
            <template #checked-icon>
              <icon-check/>
            </template>
            <template #unchecked-icon>
              <icon-close/>
            </template>
          </a-switch>
        </div>
      </div>
      <div class="analyze-container">
        <div class="user-analyze">
          <app-user-analysis :data="userRankData"/>
        </div>
        <div class="result-analyze">
          <app-result-analysis :data="resultPieData"/>
        </div>
      </div>
    </a-card>

    <a-modal
      v-model:visible="deleteDialog"
      title="删除答题应用"
      :width="300"
    >
      <div class="delete-text">
        确定删除该答题应用吗？对应答题记录，评分规则和题目都将被删除，请谨慎操作。
      </div>
      <template #footer>
        <a-button @click="deleteDialog = false">取消</a-button>
        <a-button type="primary" @click="handleDelete">删除</a-button>
      </template>
    </a-modal>

    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<style scoped>
.card, .app-analyze-card {
  margin-top: 20px;
}

.app-container {
  display: flex;
  justify-content: space-between;
}

.app-info {
  width: 80%;
}

.app-name {
  margin-top: 10px;
  font-size: 28px;
  font-weight: 600;
  color: var(--color-neutral-10);
}

.app-desc {
  margin: 10px 0;
  font-size: 14px;
  font-weight: 400;
  color: var(--color-neutral-6);
  width: 80%; /* 固定宽度 */
  word-wrap: break-word; /* 超过宽度自动换行 */
}

.app-other {
  line-height: 28px;
  color: var(--color-neutral-8)
}

.user {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.btn {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.mobile-only {
  display: none;
}

.delete-text {
  color: red;
  font-weight: 600;
  font-size: 18px;
}

.analyze-container {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.user-analyze,
.result-analyze {
  flex: 1;
  min-width: 400px;
}

.title {
  display: flex;
  height: 80px;
  gap: 10px;
}

.title .text {
  color: var(--color-text-1);
  font-size: 20px;
  font-weight: 500;
}

.title .btn {
  color: var(--color-text-3);
  font-size: 12px;
  font-weight: 400;
  height: 20px;
  line-height: 20px;
}

@media (max-width: 768px) {
  .app-container {
    flex-direction: column;
  }

  .app-info {
    width: 100%;
  }

  .app-desc {
    width: 100%;
  }

  .desk {
    display: none;
  }

  .mobile-only {
    display: block;
  }

  .user-analyze,
  .result-analyze {
    flex: 1 1 100%;
    min-width: auto;
  }
}
</style>
